package ar.edu.unq.leezsi.core;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.unq.leezsi.utils.ClassUtils;

public class CowebFilter implements Filter {

	public static FilterConfig getFilterConfig() {
		return config;
	}

	private CowebApplication application;

	private static FilterConfig config;

	@Override
	public void destroy() {
		this.getApplication().destroy();
	}

	@Override
	public void doFilter(final ServletRequest request,
			final ServletResponse response, final FilterChain chain)
			throws IOException, ServletException {
		this.getApplication().doFilter((HttpServletRequest) request,
				(HttpServletResponse) response, chain);
	}

	public CowebApplication getApplication() {
		return this.application;
	}

	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
		String appName = filterConfig.getInitParameter("application");
		if (appName != null) {
			this.setApplication(ClassUtils.<CowebApplication> wrapperForName(
					appName).newInstance());
		}
	}

	public void setApplication(final CowebApplication application) {
		this.application = application;
	}

}
